<script lang='ts' setup>
import { commonTransform } from '@/utils/transform';
import { deleteUser, searchUser, updateUser } from '@/api/user'

import type { IUser, ISearchParams } from '@/types/request'
import type { ColumnsType } from 'ant-design-vue/es/table'
import type { TransformUser, TransformValueOfUser } from '@/types/table-transform';

/**
 * 搜索框逻辑
 */
// 搜索参数
const searchParams = reactive({
  page: 1,
  size: 8,
  total: 0,
  condition: '',
})

// 对接口返回数据进行修改
function transformUser(user: IUser) {
  function handleRole() {
    let role
    switch (user.role) {
      case 'ADMIN':
        role = '管理员'
        break;
      case 'COMMON':
        role = '普通用户'
        break;
      default:
        role = '未知'
        break;
    }

    return {
      text: role,
      value: user.role,
    }
  }

  return {
    ...commonTransform(user),
    role: handleRole(),
    sex: {
      value: !!user.sex,
      text: user.sex ? '男' : '女'
    },
    pwd: {
      value: '',
      text: user.pwd ? '已设置' : '未设置',
    },
  }
}

let realDataSource = ref<TransformUser[]>([])

// 搜索方法
async function handleRequest() {
  // 请求搜索接口获取数据
  let response = await searchUser(searchParams)
  if (response.data == null) {
    searchParams.page = 1
    searchParams.condition = ''
    searchParams.size = 8
    searchParams.total = 0
    response = await searchUser(searchParams)
  }

  realDataSource.value = response.data?.current_data?.map(item => transformUser(item))

  return response
}

/**
 * 表格逻辑
 */
// 用户表格的列格式
const colums = ref<ColumnsType>([
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '手机号',
    align: 'center',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '密码',
    align: 'center',
    dataIndex: 'pwd',
    key: 'pwd',
  },
  {
    title: '位置',
    dataIndex: 'position',
    align: 'center',
    key: 'position',
  },
  {
    title: '个性签名',
    dataIndex: 'slogan',
    align: 'center',
    key: 'slogan',
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    align: 'center',
    notShowInput: true,
    showSwitch: true,
  },
  {
    title: '城市',
    dataIndex: 'city',
    align: 'center',
    key: 'city'
  },
  {
    title: '权限',
    dataIndex: 'role',
    align: 'center',
    key: 'role',
    notShowInput: true
  },
])

// 删除方法
async function handleDelete(id: string) {
  return await deleteUser(id)
}

// 编辑按钮
async function handleUpdate(toUploadData: TransformValueOfUser) {
  return await updateUser(toUploadData)
}



</script>

<template>
  <div>

    <Search name="用户" :on-search-request="handleRequest" :searchParams="searchParams" />
    <!-- 用户表格页面 -->
    <Table ref="table" :searchParams="searchParams" :expand-columns="colums" :real-data-source="realDataSource"
      :on-delete="handleDelete" :on-request="handleRequest" :on-update="handleUpdate" />
  </div>
</template>

<style lang='less' scoped></style>